<?php

namespace app\api\controller;

use app\api\service\Common;
use think\Db;
use app\api\service\Message;

/**
 * 自动执行脚本
 *
 * @author Administrator
 */
class Crontab
{
    public function test()
    {
        file_put_contents('./test.txt', date('Y-m-d H:i:s') . "\n", FILE_APPEND);
        exit;
    }

    // 检查订单状态
    public function check_order_server_reply_status()
    {
        file_put_contents('test.txt', date('Y-m-d H:i:s') . "\n", FILE_APPEND);
        Db::startTrans();
        try {
            // 获取所有状态为议价中的订单
            $orders = Db::table('mob_order_server')->alias('os')
                ->field('os.member_id, os.order_sn, os.order_price, os.remind_status, os.repair_id, os.order_receiving_time, os.id, os.lat, os.lon, m.phone as m_phone, m.openid')
                ->join('mob_member m', "os.member_id = m.id")
                ->where('os.status', 11)->select();

            foreach ($orders as $v) {
                if (time() - $v['order_receiving_time'] < 480) {
                    // 跳过
                    continue;
                }
                
                if ($v['remind_status'] == 0) {
                    // 获取维修店信息
                    $repair = Db::table('mob_repair')->alias('r')->field('r.repair_name, r.member_id, m.phone as m_phone, m.openid')
                        ->join('mob_member m', 'm.id = r.member_id')->where('r.id', $v['repair_id'])->find();

                    // 议价时间超过8分钟  提醒用户和维修店提醒一次
                    Db::table('mob_order_server')->where("id", $v['id'])->setInc('remind_status');
                    $text = '订单议价时间过长';
                    $this->msg_model($v, $repair, $text);
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            // 发送微信模板消息
            $data = [
                'touser' => 'o7vuBwEfcX2VoZDGauEAm8ReqSeY',
                'template_id' => 'rnJUnlEzUqYEEwmXLKm-U2LpMW90D-7l71DqIzp4tkY',
                'topcolor' => '#FF0000',
                'data' => [
                    'first' => [
                        'value' => '错误通知',
                        "color" => "#173177"
                    ],
                    'keyword1' => [
                        'value' => '订单议价定时脚本出错',
                        "color" => "#173177"
                    ],
                    'keyword2' => [
                        'value' => date('Y-m-d H:i:s'),
                        "color" => "#173177"
                    ],
                    'remark' => [
                        'value' => $e->getMessage(),
                        "color" => "#173177"
                    ]
                ]
            ];
            send_msg($data);
        }
    }

    // 发送消息模板
    public function msg_model($v, $repair, $text) {
        /**********
         *  提醒用户  可以延长议价时间
         *
         **/
        // 发送短信
        $params[] = $v['order_sn'];
        $param = [ 'phone' => $v['m_phone'], 'type' => 32, 'model' => 3052126, 'params' => json_encode($params)];
        Common::send_note($param);
        // 发送微信模板消息
        $url = 'http://' . $_SERVER['HTTP_HOST'] . '/wechat/orders/order_info.html?id=' . $v['id'];
        if ($v['openid']) {
            $data = [
                'touser' => $v['openid'],
                'template_id' => 'bnzQgDYgRRSaNUhN0PxIkCDzZiAaKMyX_ijEt3bjOG4',
                'url' => $url,
                'topcolor' => '#FF0000',
                'data' => [
                    'first' => [
                        'value' => '您好，您有一比订单即将议价超时',
                        "color" => "#173177"
                    ],
                    'keyword1' => [
                        'value' => $v['order_sn'],
                        "color" => "#173177"
                    ],
                    'keyword2' => [
                        'value' => $v['order_price'],
                        "color" => "#173177"
                    ],
                    'keyword3' => [
                        'value' => date('Y-m-d H:i:s'),
                        "color" => "#173177"
                    ],
                    'keyword4' => [
                        'value' => '请联系维修店，尽快完成推送',
                        "color" => "#173177"
                    ]
                ]
            ];
            send_msg($data);
        }
        // 推送站内信息
        $param = [
            'member_id' => $v['member_id'],
            'member_role' => 'member',
            'msg_id' => 45,
        ];
        $params = [
            $repair['repair_name'], $v['order_sn'], $v['order_price'], date('Y-m-d H:i:s'), 'url' => $url
        ];
        Message::creation_order_msg($param, $params);

        /*********
        *   提醒维修店   议价即将超时  请尽快完成操作 或者联系用户延长议价时间
         *
         ***/
        // 发送短信
        $params[] = $v['order_sn'];
        $param = [ 'phone' => $v['m_phone'], 'type' => 33, 'model' => 3052126, 'params' => json_encode($params)];
        Common::send_note($param);
        // 发送微信模板消息
        $url = 'http://' . $_SERVER['HTTP_HOST'] . '/wechat/r_member/order_info.html?id=' . $v['id'];
        if ($repair['openid']) {
            $data = [
                'touser' => $repair['openid'],
                'template_id' => 'bnzQgDYgRRSaNUhN0PxIkCDzZiAaKMyX_ijEt3bjOG4',
                'url' => $url,
                'topcolor' => '#FF0000',
                'data' => [
                    'first' => [
                        'value' => '您好，您有一比订单即将议价超时',
                        "color" => "#173177"
                    ],
                    'keyword1' => [
                        'value' => $v['order_sn'],
                        "color" => "#173177"
                    ],
                    'keyword2' => [
                        'value' => $v['order_price'],
                        "color" => "#173177"
                    ],
                    'keyword3' => [
                        'value' => date('Y-m-d H:i:s'),
                        "color" => "#173177"
                    ],
                    'keyword4' => [
                        'value' => '请尽快完成推送',
                        "color" => "#173177"
                    ]
                ]
            ];
            send_msg($data);
        }
        // 推送站内信息
        $param = [
            'member_id' => $v['member_id'],
            'member_role' => 'repair',
            'msg_id' => 45,
        ];
        $params = [
            $v['order_sn'], $v['order_price'], date('Y-m-d H:i:s'), 'url' => $url
        ];
        Message::creation_order_msg($param, $params);
    }

    public function distribution_money()
    {
        // 检查账单  分销账单 状态为 7  并且冻结状态为 1
        // 根据账单关联订单号检查订单是否过了售后保障期
        // 如果已经过了售后保障期说明订单彻底完成   将账单对应的冻结分销收益转为可用分销收益
        // 修改账单状态
        
    }

    // 定时推送消息
    public function timing_push_msg() {
        // 启动事务
        Db::startTrans();
        try {
            $message = Db::table('mob_message_push_log')->whereTime('timing', '>', 0)->select();
            if ($message) {
                $msg_push_ids = '';
                foreach ( $message as $m) {
                    if ($m['timing'] > time()) {
                        continue;
                    }
                    $msg = db('message')->where('id', $m['msg_id'])->find();
                    $msg_push_ids .= $m['id'] . ',';
                    $role = explode(',', $m['member_role']);
                    $terrace = explode(',', $m['terrace']);
                    $target = $m['target'];
                    $msg_id = $m['msg_id'];
                    foreach ($role as $r) {
                        switch ($target) {
                            case 'all':  // 全部用户
                                if ($r == 'member') {
                                    $ids = db('member')->column('id');  // 发送的角色是用户   获取全部用户
                                } else {
                                    $ids = Db::table('mob_member')->alias('m')->join('mob_' . $r . ' r', 'm.id = r.member_id and r.audit_status = 2')  // 根据角色发送  有申请对应角色并且状态为通过审核才能收到信息
                                    ->column('m.id');
                                }
                                break;
                            case 'member': // 指定用户
                                if (!input('?param.ids') || !input('param.ids')) {
                                    return json(['code' => 0, 'msg' => '请输入指定用户的ID']);
                                }
                                $ids = input('param.ids');
                                $ids = explode(',', $ids);    // 指定用户  默认认为指定用户满足所有角色权限
                                break;
                            default:
                                break;
                        }

                        foreach ($terrace as $v) {
                            foreach ($ids as $id) {
                                $data[] = [
                                    'member_id' => $id, // 用户ID
                                    'member_role' => $r, // 用户角色
                                    'terrace' => $v, // 平台
                                    'msg_id' => $msg_id, // 消息ID
                                    'add_time' => time(), // 发送时间
                                    'msg_type' => $msg['type'], // 订单类型
                                ];
                            }
                        }
                    }
                    // 写入用户消息表
                    Db::table('mob_member_message')->insertAll($data);
                }
                $msg_push_ids = trim($msg_push_ids, ','); // 将推送过的记录定时时间改为0
                Db::table('mob_message_push_log')->where('id', 'in', $msg_push_ids)->update(['timing' => 0]);
            }
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            // 发送微信模板消息
            $data = [
                'touser' => 'o7vuBwEfcX2VoZDGauEAm8ReqSeY',
                'template_id' => 'rnJUnlEzUqYEEwmXLKm-U2LpMW90D-7l71DqIzp4tkY',
                'topcolor' => '#FF0000',
                'data' => [
                    'first' => [
                        'value' => '错误通知',
                        "color" => "#173177"
                    ],
                    'keyword1' => [
                        'value' => '定时发送消息脚本错误',
                        "color" => "#173177"
                    ],
                    'keyword2' => [
                        'value' => date('Y-m-d H:i:s'),
                        "color" => "#173177"
                    ],
                    'remark' => [
                        'value' => $e->getMessage(),
                        "color" => "#173177"
                    ]
                ]
            ];
            send_msg($data);
            return false;
        }
    }
}
